package com.muyu.rabbitmq.consumer;

import com.muyu.rabbitmq.domain.User;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName Consumer
 * @Description 描述
 * @Author ShiYu.Cui
 * @Date 2024/4/8 16:32
 */
@Component
@Slf4j
public class Consumer {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @RabbitListener(queuesToDeclare = {@Queue("directExchange")})
    public void receive(String userName, Message message, Channel channel){
        log.info("接收到消息：{}",userName);

        try {
            //模拟处理消息
            log.info("消息确认成功");
            //手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            log.info("消息确认失败",e);
            try {
                //消息处理失败，拒绝消息重新放回队列
                log.info("消息确认失败，重新放回队列");
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException ex) {
                log.info("消息确认失败",ex);
                throw new RuntimeException(ex);
            }
        }
    }
    public static void main(String[] args) {
        User user = new User();
        user.setUserName("看看了");
        boolean ack = true;
        String cause = "cause";
        log.info("---- confirm ----ack"+ack+"causer=" +cause);
        log.info("correlationData-->"+user.toString());
        if(ack){
            //交换机接收到
            log.info("----confirm ----ack===true cause=="+cause);
        }else {
            //没有接收到
            log.info("----confirm ----ack===false cause=="+cause);
        }

    }
}
